package com.army.study.utils;

import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

public class HPermission {
    private static final int PERMISSION_CODE = 20211113;

    private OnPermissionStateListener onPermissionStateListener;
    public interface OnPermissionStateListener {
        void onPermissionGranted();
    }

    public void requestPermissions(Context context, OnPermissionStateListener onPermissionStateListener) {
        this.onPermissionStateListener = onPermissionStateListener;

        if (context.verifySelfPermission(SystemPermission.DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (context.canRequestPermission(SystemPermission.DISTRIBUTED_DATASYNC)) {
                // 是否可以申请弹框授权(首次申请或用户未选择禁止且不再提示)
                context.requestPermissionsFromUser(new String[]{SystemPermission.DISTRIBUTED_DATASYNC}, PERMISSION_CODE);
            } // 显示应用需要权限的理由, 提示用户进入设置授权
        } else {
            // 权限已被授权
            if (onPermissionStateListener != null) {
                // 调用已经实现此接口的onPermissionGranted方法
                onPermissionStateListener.onPermissionGranted();
            }
        }
    }

    /**
     * 权限回调方法
     * @param requestCode
     * @param grantResults
     */
    public void onRequestPermissionsFromUserResult(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == IBundleManager.PERMISSION_GRANTED) {
                if (onPermissionStateListener != null) {
                    onPermissionStateListener.onPermissionGranted();
                }
            }
        }
    }

















}
